package org.feiye.studyday28.case2;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

//登陆服务器
public class LoginSever {
	public static void main(String[] args) {
		// 创建一个Socket
		ServerSocket server = null;
		Socket socket = null;
		InputStream in = null;
		ObjectInputStream ois = null;
		OutputStream os = null;
		try {
			// 接收客户端请求
			server = new ServerSocket(5000);
			// 使用accept();方法来侦听并接收到此server的连接
			socket = server.accept();
			// 通过socket获得输入流，获得用户的请求
			in = socket.getInputStream();
			ois = new ObjectInputStream(in);
			User user = (User) ois.readObject();
			System.out.println("客户端说：" + user.getUserName() + "," + user.getPassWord());
			// 给客户端响应
			String reply = "欢迎进入";
			// 通过输出流讲响应发送给客户端
			os = socket.getOutputStream();
			os.write(reply.getBytes());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 释放资源
			if (os != null)
				try {
					os.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			if (ois != null)
				try {
					ois.close();
				} catch (IOException e2) {
					e2.printStackTrace();
				}
			if (in != null)
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			if (socket != null)
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			if (server != null)
				try {
					server.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}
}
